/**
 * Created by ruiyuan on 15-9-4.
 */

var mutualAidService = require('../services/mutualAidService');
var wxmutualAidService = require('../services/wxmutualAidService');
var wxjournalsService = require('../services/wxjournalsService');
var messageUtil = require('../common/utils/messageUtil');
var toolUtil = require('../common/utils/toolUtil');
var Users = mongoose.model('user');
var userService = require('../services/userService');

/*  宝宝树66小区二次改造    add   guo.xiaomin  20170807   start   */
var communityService = require('../services/communityService');
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170807   end   */
/**
 * 获取求助全部列表
 * @param req
 * @param res
 */
exports.getMutualAllList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;
    var range = req.query.range;
    var sort = req.query.sort;
    var direction = req.query.direction;

    mutualAidService.getMutualAllListService(user, ts, range, sort, direction, function (err, result) {
        if (err) {
            logger.error('Failed to getMutualAllList ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6001));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6001));
        }
    })
};

/**
 * 获取求助列表
 * @param req
 * @param res
 */
exports.getQuestionList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;
    var range = req.query.range;
    var direction = req.query.direction;
    var status = req.query.status;

    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170815   start   */
    // 管理多个小区server兼容性走查
    // 前端传递参数:选择后小区ID
    var currCommunityId = req.query.currCommunityId;

    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   start   */
    // 旧版本对应
    if(currCommunityId == undefined || currCommunityId == null || currCommunityId == '') {
        currCommunityId = user.community._id;
    }
    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   end   */

    var currCityId = user.community.cityId;
    communityService.searchCityIdByCommunityIdService(currCommunityId, function (err, data) {
        if (err) {
            logger.error('Failed to searchCityIdByCommunityIdService ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6010));
        } else {
            if (data._doc) {
                currCityId = data._doc.cityId;
            }
        }

        // mutualAidService.getQuestionListService(user, ts, range, direction, status, function (err, result) { // 旧
        mutualAidService.getQuestionListService(user, ts, range, direction, status, currCommunityId, currCityId, function (err, result) { // 新
            if (err) {
                logger.error('Failed to getQuestionList ---' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message, 6002));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result, 6002));

                if (ts == '0') {
                    var message = {
                        userId: user._id,
                        type: range == 'around' ? 12 : 13,
                        typeDesc: range == 'around' ? '邻里问问（跨小区）' : '邻里问问（本小区）',
                        deviceId: req.params.deviceId,
                        vname: req.query.vname,
                        vcode: req.query.vcode,
                        os: req.query.type,
                        createTime: new Date().getTime()
                    };
                    toolUtil.putMessageLogMQ(message);
                }
            }
        })
    });

    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170815   end   */
};

/**
 * 获取分享列表
 * @param req
 * @param res
 */
exports.getShareList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;
    var range = req.query.range;
    var direction = req.query.direction;
    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170815   start   */
    // 管理多个小区server兼容性走查
    // 前端传递参数:选择后小区ID
    var currCommunityId = req.query.currCommunityId;

    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   start   */
    // 旧版本对应
    if(currCommunityId == undefined || currCommunityId == null || currCommunityId == '') {
        currCommunityId = user.community._id;
    }
    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   end   */

    var currCityId = user.community.cityId;
    communityService.searchCityIdByCommunityIdService(currCommunityId, function (err, data) {
        if (err) {
            logger.error('Failed to searchCityIdByCommunityIdService ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6010));
        } else {
            if (data._doc) {
                currCityId = data._doc.cityId;
            }
        }

        // mutualAidService.getShareListService(user, ts, range, direction, function (err, result) { // 旧
        mutualAidService.getShareListService(user, ts, range, direction, currCommunityId, currCityId,  function (err, result) { // 新
            if (err) {
                logger.error('Failed to getShareList ---' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message, 6003));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result, 6003));

                if (ts == '0') {
                    var message = {
                        userId: user._id,
                        type: range == 'around' ? 14 : 15,
                        typeDesc: range == 'around' ? '随便说说（跨小区）' : '随便说说（本小区）',
                        deviceId: req.params.deviceId,
                        vname: req.query.vname,
                        vcode: req.query.vcode,
                        os: req.query.type,
                        createTime: new Date().getTime()
                    };
                    toolUtil.putMessageLogMQ(message);
                }
            }
        })
    });
    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170815   end   */
};

/**
 * 获取闲聊列表
 * @param req
 * @param res
 */
exports.getTalkList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;
    var range = req.query.range;
    var direction = req.query.direction;

    mutualAidService.getTalkListService(user, ts, range, direction, function (err, result) {
        if (err) {
            logger.error('Failed to getTalkList ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6004));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6004));
        }
    })
};


/**
 * 获取回复列表
 * @param req
 * @param res
 */
exports.getReplyList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;
    var id = req.params.id;

    mutualAidService.getReplyListService(user, ts, id, function (err, result) {
        if (err) {
            logger.error('Failed to getReplyList ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6005));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6005));
        }
    })
};


exports.getMyAdoptReplyList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;

    mutualAidService.getMyAdoptReplyListService(user, ts, function (err, result) {
        if (err) {
            logger.error('Failed to getMyAdoptReplyList ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6006));
        } else {
            var data = {
                ts: result.length > 0 ? result[result.length - 1]._doc.dateReplied.getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                list: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 6006));
        }
    });
};

exports.getMyReplyList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;

    mutualAidService.getMyReplyListService(user, ts, function (err, result) {
        if (err) {
            logger.error('Failed to getMyAdoptReplyList ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6007));
        } else {
            var data = {
                ts: result.length > 0 ? result[result.length - 1]._doc.dateReplied.getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                list: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 6007));
        }
    });
};

exports.getEssenceList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;
    var range = req.query.range;

    mutualAidService.getEssenceListService(user, ts, range, function (err, result) {
        if (err) {
            logger.error('Failed to getEssenceList ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6008));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6008));

            if (ts == '0') {
                var message = {
                    userId: user._id,
                    type: range == 'around' ? 37 : 38,
                    typeDesc: range == 'around' ? '66精选（全城）' : '66精选（本小区）',
                    deviceId: req.params.deviceId,
                    vname: req.query.vname,
                    vcode: req.query.vcode,
                    os: req.query.type,
                    createTime: new Date().getTime()
                };
                toolUtil.putMessageLogMQ(message);
            }
        }
    });
};


exports.getMutualAidTables = function (req, res) {
    var user = req.user;

    mutualAidService.getMutualAidTablesService(user, function (err, result) {
        if (err) {
            logger.error('Failed to getMyAdoptReplyList ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6009));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6009));
        }
    })
};

exports.getMutualAidPageData = function (req, res) {

    var user = req.user;
    var ts = req.params.ts;
    var category = req.query.category;
    var direction = req.query.direction;
    var parentCommunity = req.query.parentCommunity;

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   start   */
// 前端选择其他小区
    // redis保存取得用户选择小区ID,城市ID
    var currUserId = user._id; // 用户ID

    // 前端传递参数:选择后小区ID
    var currCommunityId = req.query.currCommunityId;

    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   start   */
    // 旧版本对应
    if(currCommunityId == undefined || currCommunityId == null || currCommunityId == '') {
        currCommunityId = user.community._id;
    }
    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   end   */

    var currCityId = user.community.cityId;

    redisClient.set(currUserId + ":currCommunityId", currCommunityId, function(setErr, setReply) {
        if (setErr) return false;
        redisClient.EXPIRE(currUserId + ":currCommunityId", 86400, function(expireErr, expireReply) {
            if (expireErr) return false;
        });
    });

    redisClient.set(currUserId + ":currCityId", currCityId, function(setErr, setReply) {
        if (setErr) return false;
        redisClient.EXPIRE(currUserId + ":currCityId", 86400, function(expireErr, expireReply) {
            if (expireErr) return false;
        });
    });

    communityService.searchCityIdByCommunityIdService(currCommunityId, function (err, data) {
        if (err) {
            logger.error('Failed to getMyAdoptReplyList ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6010));
        } else {
            // currCityId = JSON.stringify(result._doc.cityId);
            if(data && data._doc) {
                currCityId = data._doc.cityId;
                redisClient.set(currUserId + ":currCityId", currCityId, function(setErr, setReply) {
                    if (setErr) return false;
                    redisClient.EXPIRE(currUserId + ":currCityId", 86400, function(expireErr, expireReply) {
                        if (expireErr) return false;
                    });
                });
            }
            mutualAidService.getMutualAidPageDataService(user, ts, category, direction, parentCommunity, currCommunityId, currCityId, function (err, result) {

                /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   end   */
                if (err) {
                    logger.error('Failed to getMyAdoptReplyList ---' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message, 6010));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, result, 6010));
                }
            });
        }
    });
};

exports.getWXCommunityMsgList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;
    var direction = req.query.direction;

    wxmutualAidService.getWXCommunityMsgListService(user, ts, direction, function (err, result) {
        if (err) {
            logger.error('Failed to getWXCommunityMsgList ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6011));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6011));
        }
    });
};

exports.getWXMyCommunityMsgList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;
    var direction = req.query.direction;
    var uid = req.query['userid'];
    var vCode = req.cparams.vcode;

    if (uid && uid != user._id) {
        userService.findByIdService(uid, vCode, function (err, other) {
            if (err) {
                logger.error('getWXCommunityMsgList uid ---' + err.message, uid);
                res.json(messageUtil.composeFailedMessage(req, err.message, 6012));
            } else {
                user = other;
                wxmutualAidService.getWXMyCommunityMsgListService(user, ts, direction, function (err, result) {
                    if (err) {
                        logger.error('Failed to getWXCommunityMsgList ---' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 6012));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, result, 6012));
                    }
                });
            }
        })
    } else {

        wxmutualAidService.getWXMyCommunityMsgListService(user, ts, direction, function (err, result) {
            if (err) {
                logger.error('Failed to getWXCommunityMsgList ---' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message, 6012));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result, 6012));
            }
        });
    }
};

exports.getWXJournalsList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;
    var direction = req.query.direction;

    wxjournalsService.getWXJournalsService(user, ts, direction, function (err, result) {
        if (err) {
            logger.error('Failed to getWXMyJournalsList ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6013));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6013));
        }
    });
};

exports.getWXMyJournalsList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;
    var direction = req.query.direction;
    var uid = req.query['userid'];
    var vCode = req.cparams.vcode;

    if (uid && uid != user._id) {
        userService.findByIdService(uid, vCode, function (err, other) {
            if (err) {
                logger.error('getWXMyJournalsList failed for uid ---' + err.message, uid);
                res.json(messageUtil.composeFailedMessage(req, err.message, 6014));
            } else {
                user = other;
                wxjournalsService.getWXMyJournalsService(user, ts, direction, function (err, result) {
                    if (err) {
                        logger.error('Failed to getWXMyJournalsList ---' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 6014));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, result, 6014));
                    }
                });
            }
        })
    } else {
        wxjournalsService.getWXMyJournalsService(user, ts, direction, function (err, result) {
            if (err) {
                logger.error('Failed to getWXMyJournalsList ---' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message, 6014));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result, 6014));
            }
        });
    }
};

exports.getWXReplyList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;
    var direction = req.query.direction;
    var id = req.params.id;
    var lang = req.cparams.lang;

    wxmutualAidService.getWXReplyListService(user, ts, id, function (err, result) {
        if (err) {
            logger.error('Failed to getWXReplyList ---' + err.message);
            if (lang && err['message_' + lang])
                res.json(messageUtil.composeFailedMessage(req, err['message_' + lang], 6015));
            else
                res.json(messageUtil.composeFailedMessage(req, err.message, 6015));

            // res.json(messageUtil.composeFailedMessage(req, err.message, 6015));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6015));
        }
    });
};

exports.getWXSnapshotUpdate = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;

    wxmutualAidService.getWXSnapshotUpdateService(user, ts, function (err, result) {
        if (err) {
            logger.error('Failed to getWXSnapshotUpdate ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6016));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6016));
        }
    });
};

exports.getWXMyRepliedGoods = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;

    wxmutualAidService.getWXMyRepliedGoodsService(user, ts, function (err, result) {
        if (err) {
            logger.error('Failed to getWXMyRepliedGoods ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6017));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6017));
        }
    });
};

exports.getWXReplyListener = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;
    var id = req.params.id;

    wxmutualAidService.getWXReplyListenerService(user, ts, id, function (err, result) {
        if (err) {
            logger.error('Failed to getWXSnapshotUpdate ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6018));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6018));
        }
    });
};

exports.getJournalsUserNotification = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;

    wxjournalsService.getJournalsUserNotificationService(user, ts, function (err, result) {
        // wxmutualAidService.getJournalsUserNotificationService(user, ts, function (err, result) {
        if (err) {
            logger.error('Failed to getJournalsNotificationService ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6019));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6019));
        }
    });
};

exports.getJournalsCommunityNotification = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;

    wxjournalsService.getJournalsCommunityNotificationService(user, ts, function (err, result) {
        if (err) {
            logger.error('Failed to getJournalsNotificationService ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6022));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6022));
        }
    });
};

exports.getJournalsNotification = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;

    wxjournalsService.getJournalsNotificationService(user, ts, function (err, result) {
        if (err) {
            logger.error('Failed to getJournalsNotificationService ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6022));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6022));
        }
    });
};


exports.getJournalsPics = function (req, res) {
    // var user = req.user;
    var uid = req.query.userid;
    var vCode = req.cparams.vcode;

    userService.findByIdService(uid, vCode, function (err, other) {
        if (err) { // other will NEVER be null, if can't find user, it will be err.
            logger.error('getJournalsPics failed for uid ---' + err.message, uid);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6020));
        } else {
            wxjournalsService.getJournalsPicsService(other, function (err, result) {
                if (err) {
                    logger.error('Failed to getJournalsPicsService ---' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message, 6020));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, result, 6020));
                }
            });
        }
    })

};

exports.getMyMessageList = function (req, res) {
    var user = req.user;
    var page = req.params.page;

    wxjournalsService.getMyMessageListService(user, page, function (err, result) {
        if (err) {
            logger.error('Failed to getMyMessageListService ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 6021));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 6021));
        }
    });
};

